<?php
namespace control;
/*
*附件类
*/

class fileClass extends adIndexClass
{
    private const title = '附件类';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'homeSearch':
                $tr = [
                    'target'          => [
                        'name'  => '对象',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'staff' => [
                        'name'  => "上传人",
                        'width' => 200,
                    ],
                    'name'  => [
                        'name'  => "附件名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'secret'         => [
                        'name'  => '保密',
                        'width' => 200,
                    ],
                    'format'          => [
                        'name'  => '格式',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'size'          => [
                        'name'  => '体积',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => '上传时间',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'staff' => [
                        'name'  => "上传者",
                        'width' => 250,
                    ],
                    'name'  => [
                        'name'  => "附件名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'secret'         => [
                        'name'  => '保密',
                        'width' => 250,
                    ],
                    'format'          => [
                        'name'  => '类型',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'size'          => [
                        'name'  => '体积',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => '上传时间',
                        'width' => 250,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    "对象" => repeatSelect(array('sqlForm' => 'file', 'sqlField' => 'target', 'name' => 'target')),
                    "附件名称"   => text(array("name" => "name")),
                    '上传日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
            ]
        ];
        if ($this->power("file", "seeAll")) {
            $array[0][] = ['上传人' => $this->staffSelect(array("show" => 4))];
        }
        if ($this->power("file", "seeSecret")) {
            $array[0][] = ['保密' => select(["name" => "secret", "option" => array("是", "否")])];
        }
        //生成查询表单
        $html = $this->tableShow($array,1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*知识管理-附件管理-列表页-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power('file', 'edit')) {
            $button = "<span class='spanButton' onclick=\"layer('file','clearFile',{})\">清除无效附件</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*知识管理-附件管理-列表页-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//附件名称
        );
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//上传人
            "secret" => $this->post('secret'),//保密
            "target" => $this->post('target'),//对象
        );
        //对象
        $and = "";
        if (!$this->power("file", "seeSecret")) {
            $and .= " and secret = '否'";
        }
        if (!$this->power("file", "seeAll")) {
            $and .= " and stid = '" . $this->control['stid'] . "'";
        }
        //发生时间-开始日期
        if (!empty($this->post('startDay'))) {
            $startDay = $this->post('startDay') . " 00:00:00";
            $and .= " and time >= '$startDay' ";
        }
        //发生时间-结束日期
        if (!empty($this->post('endDay'))) {
            $endDay = $this->post('endDay') . " 23:59:59";
            $and .= " and time <= '$endDay' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = $and . search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => "file", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "fileId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
//				"box"      => array("name" => "fileId", "value" => $array['id']),
                "download" => array("name" => $array['name'], "href" => $array['src']),
            );
            if (in_array($array['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                $dominate['preview'] = array("format" => $array['format'], "name" => $array['name'], "href" => $array['src']);
            } elseif (in_array($array['format'], array("png", "gif", "jpg"))) {
                $dominate['img'] = array("title" => "在线预览", "href" => $array['src']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "size":
                        $row[] = self::formatSize($array['size']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
            //数据准备
//            if ($array['target'] == "事务") {
//                $affair = query("affair", "id = '$array[targetId]'");
//                $name = $affair['name'];
//                if ($affair['stid'] == $this->control['stid'] or $this->power("affair", "seeAll")) {
//                    $dominate['affair'] = array("title" => "工作事务详情","click" => "newIframe('工作事务详情','".root."control/adIndex.html?cla=affair&fun=detail&id=".$affair['id']."')");
//                }
//            } elseif ($array['target'] == "客户") {
//                $kehu = query("kehu", "khid = '$array[targetId]'");
//                $name = $kehu['companyName'];
//                if ($kehu['stid'] == "公客" or in_array($this->control['stid'], explode(",", $kehu['edit'])) or $this->power("client", "seeAll")) {
//                    $dominate['client'] = array("title" => "客户详情","click" => "newIframe('客户详情','".root."control/adIndex.html?cla=client&fun=detail&menu=clientFile&id=".$kehu['khid']."')");
//                }
//            } elseif ($array['target'] == "订单") {
//                $buyCar = query("buycar", "id = '$array[targetId]'");
//                $name = $buyCar['name'];
//                if ($buyCar['stid'] == $this->control['stid'] or $this->power("order", "seeAll")) {
//                    $dominate['order'] = array("title" => "订单详情","click" => "newIframe('订单详情','".root."control/adIndex.html?cla=order&fun=detail&menu=orderFile&id=".$buyCar['id']."')");
//                }
//            } elseif ($array['target'] == "项目") {
//                $project = query("project", "id = '$array[targetId]'");
//                $name = $project['name'];
//                if ($this->power("project", "see")) {
//                    $dominate['project'] = array("title" => "项目详情","click" => "newIframe('项目详情','".root."control/adIndex.html?cla=project&fun=detail&menu=projectFile&id=".$project['id']."')");
//                }
//            }
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    public function clearFile()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "提示：" => "是否确认清除无效附件？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "清除附件", "height" => 200, "html" => $html));
    }

    /** 删除所有空目录
     * @param String $path 目录路径
     */

    public function rm_empty_dir(string $path)
    {

        if (is_dir($path) && ($handle = opendir($path)) !== false) {
            while (($file = readdir($handle)) !== false) {     // 遍历文件夹
                if ($file != '.' && $file != '..') {
                    $curfile = $path . '/' . $file;          // 当前目录
                    if (is_dir($curfile)) {                // 目录
                        $this->rm_empty_dir($curfile);          // 如果是目录则继续遍历
                        if (count(scandir($curfile)) == 2) { // 目录为空,=2是因为. 和 ..存在
                            rmdir($curfile);             // 删除空目录
                        }
                    }
                }
            }
            closedir($handle);
        }
    }

    public function clearFileEdit(): bool|string
    {
        $all = find(array('table' => 'file', 'where' => "1=1 order by time asc"));
        $x = 0;
        $text = '';
        foreach ($all['array'] as $array) {
            if (!file_exists(serverRoot . $array['src']) || empty($array['targetId'])) {
                @unlink(serverRoot . $array['src']);
                delete(array('table' => 'file', 'where' => "id = '$array[id]'"));
                $x++;
                $text .= $array['name'] . "<br>";
            }
        }
        $this->rm_empty_dir(serverRoot.'file');//清除空文件夹
        if ($text) {
            $text = $this->control['name'] . '清除了无效附件如下：<br>' . $text;
            $this->logText(["type" => 'file', "text" => $text]);
        }
        $json['warn'] = 2;
        $_SESSION['warn'] = '成功清除' . $x . '个无效附件';
        return json_encode($json, 320);
    }

    /**
     * 委外合同
     * @return bool|string
     */
    public function outsourceContractFile(): bool|string
    {
        $power = [];
        if ($this->power("outsourceContract", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("outsourceContract", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "委外合同", "targetId" => $this->get('id'), "power" => $power));
    }

    /**
     * 采购合同
     * @return bool|string
     */
    public function purchaseContractFile(): bool|string
    {
        $power = [];
        if ($this->power("purchaseContract", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("purchaseContract", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "采购合同", "targetId" => $this->get('id'), "power" => $power));
    }

    /**
     * 设备
     *
     * @return false|string
     */
    public function equipmentFile()
    {
        $power = [];
        if ($this->power("equipment", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("equipment", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "设备", "targetId" => $this->get('id'), "power" => $power));
    }

    /*客户管理-客户列表-客户附件-查询条件*/
    public function clientFile()
    {
        $power = [];
        $kehu = query("kehu", "khid = '" . $this->get('id') . "'");
        if (in_array($this->control['stid'], explode(",", $kehu['see'])) || $this->power("client", "seeAll")) {
            if ($this->power("client", "fileAdd")) {
                $power[] = "新增";
            }
            if ($this->power("client", "fileDel")) {
                $power[] = "删除";
            }
        }
        return $this->fileList(array("target" => "客户", "targetId" => $this->get('id'), "power" => $power));
    }

    /*线索-查询条件*/
    public function clueFile()
    {
        $power = [];
        $info = query("clue", "id = '" . $this->get('id') . "'");
        if (in_array($this->control['stid'], explode(",", $info['see']))) {
            if ($this->power("clue", "fileAdd")) {
                $power[] = "新增";
            }
            if ($this->power("clue", "fileDel")) {
                $power[] = "删除";
            }
        }
        return $this->fileList(array("target" => "线索", "targetId" => $this->get('id'), "power" => $power));
    }

    /*商机-查询条件*/
    public function opportunityFile()
    {
        $info = query("opportunity", "id = '" . $this->get('id') . "'");
        $power = [];
        if (in_array($this->control['stid'], explode(",", $info['see']))) {
            if ($this->power("opportunity", "fileAdd")) {
                $power[] = "新增";
            }
            if ($this->power("opportunity", "fileDel")) {
                $power[] = "删除";
            }
        }
        return $this->fileList(array("target" => "商机", "targetId" => $this->get('id'), "power" => $power));
    }

    /*销售合同-查询条件*/
    public function salesContractFile()
    {
        $power = [];
        if ($this->power("salesContract", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("salesContract", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "销售合同", "targetId" => $this->get('id'), "power" => $power));
    }
    /*物料档案-查询条件*/
    public function materialFile()
    {
        $power = [];
        if ($this->power("material", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("material", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "物料档案", "targetId" => $this->get('id'), "power" => $power));
    }
    /*供应商-查询条件*/
    public function supplierFile()
    {
        $power = [];
        $info = query("supplier", "id = '" . $this->get('id') . "'");
        if ($this->control['stid'] == $info['stid'] || $this->power("supplier", "seeAll")) {
            if ($this->power("supplier", "fileAdd")) {
                $power[] = "新增";
            }
            if ($this->power("supplier", "fileDel")) {
                $power[] = "删除";
            }
        }
        return $this->fileList(array("target" => "供应商", "targetId" => $this->get('id'), "power" => $power));
    }
    public function laborCompanyFile()
    {
        $power = [];
        if ($this->power("laborCompany", "fileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("laborCompany", "fileDel")) {
            $power[] = "删除";
        }
        return $this->fileList(array("target" => "派遣单位", "targetId" => $this->get('id'), "power" => $power));
    }

    /*客户管理-订单列表-订单附件-查询条件*/
    public function orderFile()
    {
        $power = [];
        $buyCar = query("buycar", " id = '" . $this->get('id') . "' ");
        if ($buyCar['workFlow'] == "草稿" and $buyCar['stid'] == $this->control['stid']) {
            if ($this->power("order", "fileAdd")) {
                $power[] = "新增";
            }
            if ($this->power("order", "fileDel")) {
                $power[] = "删除";
            }
        }
        return $this->fileList(array("target" => "订单", "targetId" => $this->get('id'), "power" => $power));
    }

    /*项目管理-项目列表-项目附件*/
    public function projectFile()
    {
        $power = [];
        return $this->fileList(array("target" => "项目", "targetId" => $this->get('id'), "power" => $power));
    }

    /*个人中心-订单任务-项目附件-查询条件*/
    public function allotFile()
    {
        $power = [];
        if ($this->power("orderAllot", "projectFileAdd")) {
            $power[] = "新增";
        }
        if ($this->power("orderAllot", "projectFileDel")) {
            $power[] = "删除";
        }
        $buyCarAllot = query("buycar_allot", "id = '" . $this->get('id') . "'");
        return $this->fileList(array("target" => "项目", "targetId" => $buyCarAllot['projectId'], "power" => $power));
    }

    /*个人中心-订单任务-合同附件-查询条件*/
    public function allotOrderFile()
    {
        $power = [];
        $buyCarAllot = query("buycar_allot", " id = '" . $this->get('id') . "' ");
        return $this->fileList(array("target" => "订单", "targetId" => $buyCarAllot['buyCarId'], "power" => $power));
    }

    /**
     * Desc :
     * User : you name
     * Date : 2024-02-06 16:17
     * @param bool $isAsync
     * @param array $data
     * @return false|string
     */
    public function fileSearch($isAsync = true, $data = [])
    {
        $target = isset($data['target']) && $data['target'] ? $data['target'] : $this->post('target');
        $targetId = isset($data['targetId']) && $data['targetId'] ? $data['targetId'] : $this->post('targetId');
        $array = [
            [
                [
                    "附件名称" => text(array("name" => "name")).
                        hidden(array("name" => "target", "value" => $target)) .
                        hidden(array("name" => "targetId", "value" => $targetId)),
                    "保密"   => select(array("name" => "secret", "option" => array("是", "否"))),
                ],
                [
                    '上传日期'  => text(array("name" => "startDay", "laydate" => [])) . "\n-\n" .
                        text(array("name" => "endDay", "laydate" => [])),
                ]
            ]
        ];
        if ($target == '销售合同') {
            $array[0][0]['员工'] = selectMultiple(['table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'stid', 'class' => 'width200']);
        } else {
            $array[0][] = [
                '员工' => $this->staffSelect(array("show" => 4))
            ];
        }
        $html =  $this->tableShow($array);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*附件列表-查询条件
    $data = array(
        "target" => "附件对象：事务、客户、订单、项目",
        "targetId" => "对象ID",
    );
    */
    public function fileList($data)
    {
        $html = $this->fileSearch(false, $data);
        $formName = $this->get('fun') . "SearchInfoForm";
        //控件
        $button = "";
        $fileId = self::getId();
        if (in_array("新增", (array)$data['power'])) {
            $button .= "<span class='spanButton' onclick=\"document.{$fileId}form.img.click()\">添加附件</span>\n";
            /*$button .= "
			<span class='spanButton' title='添加附件' onclick=\"document.fileUpForm.file.click()\">添加附件</span>
			<form name='fileUpForm' class='hide' method='post' enctype='multipart/form-data' action='" . root . "control/adIndex.html?cla=file&fun=fileUpload'>
				<input name='file' type='file' onchange='document.fileUpForm.submit()'>
				<input name='target' type='hidden' value='" . $data['target'] . "'>
				<input name='targetId' type='hidden' value='" . $data['targetId'] . "'>
			</form>
			";*/
        }
        if (in_array("删除", (array)$data['power'])) {
            $button .= "<span class='spanButton' title='勾选并批量删除附件' onclick=\"pasWarn('" . $formName . "','file','delete')\">删除所选</span>\n";
        }
        $json['html'] = $this->search(
                $html,
                layout: 'pop',
                toolButton: $button,
                searchOption: "{target:'".$data['target']."',targetId:'".$data['targetId']."'}",
                resetFun: 'fileSearch'
            ).
            $this->uploadHtml($data['target'], $data['targetId'], $fileId, $this->root . 'control/adIndex.html?cla=file&fun=chunkUpload') .
            $this->dragUploadHtml($data['target'], $data['targetId'], $this->root . 'control/adIndex.html?cla=file&fun=chunkUpload', 'body');
        return json_encode($json, 320);
    }

    /**
     * Desc : 显示上传控件
     * User : you name
     * Date : 2024-02-22 11:45
     * @param $target
     * @param $targetId
     * @param $fileId
     * @param $url
     * @return string
     */
    public function uploadHtml($target, $targetId, $fileId, $url)
    {
        $formName = $fileId . 'form';
        return '
            <div class="hide">
                <form name="' . $formName . '" method="post" enctype="multipart/form-data">
                    <input name="img" type="file" multiple onchange="choiceFileUpload(this, \'' . $target . '\', \'' . $targetId . '\', \'' . $url . '\')">
                    <input name="target" type="hidden" value="' . $target . '">
                    <input name="targetId" type="hidden" value="' . $targetId . '">
                </form>
            </div>' .
            "<script>
                function choiceFileUpload(e, target, targetId, url) {
                    var fileList = $(e).prop('files'); //获取文件对象
                    var arr = [];
                    const chunkSize = 5 * 1024 * 1024;
                    $.each(fileList,function(n,file){
                        var value = {
                            'code':  CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
                            'target':  target,
                            'name':  file.name,
                            'size':  file.size,
                            'target_id':  targetId,
                            'chunks':  Math.ceil(file.size / chunkSize),
                            'power':  'share',
                            'error':  '',
                        }
                        arr.push(value)
                    });
                    $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo:JSON.stringify(arr)}, function (res) {
                        if(res.warn === 2){
                            layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1  })
                            //分片上传
                            for (var i = 0; i < res.data.length; i++) {
                                uploadChunks(fileList[i], res.data[i], url)
                            }
                        }else{
                            msg(res.warn, 'error')
                        }
                    }, 'json')
                }
            </script>";
    }

    /**
     * Desc : 拖拽上传
     * User : you name
     * Date : 2024-02-21 09:38
     * @param $target
     * @param $targetId
     * @param $url
     * @param $node
     * @return string
     */
    public function dragUploadHtml($target, $targetId, $url, $node)
    {
        return "
    <div id='windowMaskView' class='maskView'></div>
    <div id='maskViewContent' class='viewContent'>
        <div class='content-div'>
            <div class='upload-tips'>						
                <div class='cloud-icon'>							
                    <i class='icon-cloud cloud1 moveLeftLoop'></i>
                    <i class='icon-cloud cloud2'></i>
                    <i class='icon-cloud cloud3 moveLeftLoop'></i>
                </div>
                <div class='cloud-moveup'>
                    <i class='moveTopLoop icon-circle-arrow-up'></i>
                </div>						
                <div class='msg'>松开即可上传!</div>
            </div>
        </div>
    </div>
    <script>
        var target = '{$target}'
        var targetId = '{$targetId}'
        var url = '{$url}'
        var node = '{$node}'
        $(document).ready(function(){
            let elemetnNode=''//最后一次节点
            //要想实现拖拽，首页需要阻止浏览器默认行为，一个四个事件。
            $('#'+node).on({
                dragleave:function(e){		//拖离
                    e.preventDefault();     //移除原有浏览器监听效果
                    if(elemetnNode===e.target)
                    $('.maskView,.viewContent').removeClass('over');
                },
                drop:function(e){			//拖后放
                    e.preventDefault();     //移除原有浏览器监听效果
                },
                dragenter:function(e){		//拖进
                    elemetnNode=e.target;
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskView,.viewContent').addClass('over');
                },
                dragover:function(e){		//拖来拖去
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskView,.viewContent').addClass('over');
                }
            });
            
            //================上传的实现
            var box = document.getElementById(node); //获得到框体
            var newHandle = function(e){
                e.preventDefault(); //取消默认浏览器拖拽效果
                e.stopPropagation()
                var fileList = e.dataTransfer.files; //获取文件对象
                //fileList.length 用来获取文件的长度（其实是获得文件数量）
                console.log(fileList)
                
                //检测是否是拖拽文件到页面的操作
                if(fileList.length == 0){
                    $('.maskView,.viewContent').removeClass('over');
                    return;
                }
                var arr = [];
                const chunkSize = 5 * 1024 * 1024;
                $.each(fileList,function(n,file){
                    var value = {
                        'code':  CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
                        'target':  target,
                        'name':  file.name,
                        'size':  file.size,
                        'target_id':  targetId,
                        'chunks':  Math.ceil(file.size / chunkSize),
                        'power':  'share',
                        'error':  '',
                    }
                    arr.push(value)
                });
                $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo:JSON.stringify(arr)}, function (res) {
                    $('.maskView,.viewContent').removeClass('over');
                    if(res.warn === 2){
                        layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1 })
                        //分片上传
                        for (var i = 0; i < res.data.length; i++) {
                            uploadChunks(fileList[i], res.data[i], url)
                        }
                        box.removeEventListener(\"drop\",newHandle);
                    }else{
                        msg(res.warn, 'error')
                    }
                }, 'json')
            }
            box.addEventListener(\"drop\",newHandle,false);
        });
            
    </script>";
    }

    /*委外合同-查询结果*/
    public function outsourceContractFileSearch()
    {
        $info = query("outsource_contract", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此合同";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }
    /*采购合同-查询结果*/
    public function purchaseContractFileSearch()
    {
        $info = query("purchase_contract", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此合同";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*设备-查询结果*/
    public function equipmentFileSearch()
    {
        $info = query("equipment", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此设备";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-客户附件-查询结果*/
    public function clientFileSearch()
    {
        $kehu = query("kehu", "khid = '" . $this->post('targetId') . "'");
        if (empty($kehu['khid'])) {
            $json['html'] = "未找到此客户";
        } elseif (!in_array($this->control['stid'], explode(",", $kehu['see'])) and !$this->power("client", "seeAll")) {
            $json['html'] = "这不是你的客户，也不是协作人，也没有查看所有客户的权限";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*商机附件-查询结果*/
    public function opportunityFileSearch()
    {
        $info = query("opportunity", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此商机";
        } elseif (!in_array($this->control['stid'], explode(",", $info['see'])) and !$this->power("opportunity", "seeAll")) {
            $json['html'] = "这不是你的商机，也不是协作人，也没有查看所有商机的权限";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*销售合同附件-查询结果*/
    public function salesContractFileSearch()
    {
        $info = query("sales_contract", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此销售合同";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*物料档案附件-查询结果*/
    public function materialFileSearch()
    {
        $info = query("material", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此物料档案信息";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }
    /*供应商附件-查询结果*/
    public function supplierFileSearch()
    {
        $info = query("supplier", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此供应商信息";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    public function laborCompanyFileSearch()
    {
        $info = query("labor_company", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此派遣单位信息";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*线索附件-查询结果*/
    public function clueFileSearch()
    {
        $info = query("clue", "id = '" . $this->post('targetId') . "'");
        if (empty($info['id'])) {
            $json['html'] = "未找到此线索";
        } elseif ($info['manager'] != self::$stid and !in_array($this->control['stid'], explode(",", $info['collaborator'])) and !$this->power("clue", "seeAll")) {
            $json['html'] = "这不是你的线索，也不是协作人，也没有查看所有线索的权限";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*客户管理-订单列表-订单附件-查询结果*/
    public function orderFileSearch()
    {
        $buyCar = query("buycar", " id = '" . $this->post('targetId') . "' ");
        if (empty($buyCar['id'])) {
            $json['html'] = "未找到此订单";
        } elseif ($buyCar['stid'] != $this->control['stid'] and !$this->power("order", "seeAll")) {
            $json['html'] = "查看权限不足";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*项目管理-项目详情-项目附件-查询结果*/
    public function projectFileSearch()
    {
        $project = query("project", " id = '" . $this->post('targetId') . "' ");
        if (empty($project['id'])) {
            $json['html'] = "未找到此项目";
        } elseif (!$this->power("project", "see")) {
            $json['html'] = "查看权限不足";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*个人中心-订单任务-项目附件-查询结果*/
    public function allotFileSearch()
    {
        $project = query("project", " id = '" . $this->post('targetId') . "' ");
        if (empty($project['id'])) {
            $json['html'] = "未找到此项目";
        } elseif (!$this->power("orderAllot", "see")) {
            $json['html'] = "查看权限不足";
        } elseif (sqlNum("buycar_allot", "stid = '" . $this->control['stid'] . "' and projectId = '" . $this->post('targetId') . "'") == 0) {
            $json['html'] = "此项目没有你的任务";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }

    /*个人中心-订单任务-订单附件-查询结果*/
    public function allotOrderFileSearch()
    {
        $buyCar = query("buycar", " id = '" . $this->post('targetId') . "' ");
        if (empty($buyCar['id'])) {
            $json['html'] = "未找到此订单";
        } elseif (!$this->power("orderAllot", "see")) {
            $json['html'] = "查看权限不足";
        } elseif (sqlNum("buycar_allot", "buyCarId = '" . $this->post('targetId') . "'") == 0) {
            $json['html'] = "此订单没有你的任务";
        } else {
            $power = [];
            $json['html'] = $this->fileListSearch($power);
        }
        return json_encode($json, 320);
    }
    /*附件列表-查询结果*/
    public function fileListSearch($power)
    {
        //参数准备
        $formName = $this->get('fun') . "InfoForm";
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//附件名称
        );
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//负责人
            "secret" => $this->post('secret'),//保密
        );
        //对象
        $and = "target = '" . $this->post('target') . "' and targetId = '" . $this->post('targetId') . "'";
        //发生时间-开始日期
        if (!empty($this->post('startDay'))) {
            $startDay = $this->post('startDay') . " 00:00:00";
            $and .= " and time >= '$startDay' ";
        }
        //发生时间-结束日期
        if (!empty($this->post('endDay'))) {
            $endDay = $this->post('endDay') . " 23:59:59";
            $and .= " and time <= '$endDay' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = $and . search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => "file", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll($formName, "fileId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "fileId", "value" => $array['id']),
                "download" => array("name" => $array['name'], "href" => $array['src']),
            );
            if (in_array($array['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                $dominate['preview'] = array("format" => $array['format'], "name" => $array['name'], "href" => $array['src']);
            } elseif (in_array($array['format'], array("png", "gif", "jpg"))) {
                $dominate['img'] = array("title" => "在线预览", "href" => $array['src']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "secret":
                        if ($array['stid'] == $this->control['stid']) {
                            if ($array['secret'] == "是") {
                                $secretTitle = "点击调整为否";
                            } else {
                                $secretTitle = "点击调整为是";
                            }
                            $secret = "<span class='spanButton' title='" . $secretTitle . "' id='" . $array['id'] . "' onclick=\"fileSecret(this)\">" . ($array['secret'] ?: '否') . "</span>";
                        } else {
                            $secret = $array['secret'] ?: '否';
                        }
                        $row[] = $secret;
                        break;
                    case "size":
                        $row[] = self::formatSize($array['size']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        return $page['hint'] . "<form name='" . $formName . "'>" . $li . "</form>" . $page['button'];
    }

    /*切换保密状态*/
    public function fileSecret()
    {
        //数据准备
        $file = query("file", "id = '" . $this->post('id') . "'");
        //判断
        if (empty($this->post('id'))) {
            $json['warn'] = "附件ID为空";
        } elseif (empty($file['id'])) {
            $json['warn'] = "未找到此附件";
        } elseif ($file['stid'] != $this->control['stid']) {
            $json['warn'] = "这不是你上传的附件";
        } else {
            if ($file['secret'] == "是") {
                $json['secret'] = "否";
                $json['title'] = "点击设定为是";
            } else {
                $json['secret'] = "是";
                $json['title'] = "点击设定为否";
            }
            update(array(
                "table" => "file",
                "field" => array(
                    "secret" => $json['secret'],
                    "updateTime" => date("Y-m-d H:i:s"),
                ),
                "where" => "id = '$file[id]'",
            ));
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 上传附件
     */
    public function chunkUpload()
    {
        $powerType = '';
        $locationUrl = '';
        $file            = $_FILES['file'] ?? [];
        $info            = json_decode($_POST['info'], true);
        $state           = 0;
        $json            = [];
        $limitType       = explode(',', para('fileFormat'));
        $suffix          = self::getExtension($this->post('name'));
        $upload_progress = query("upload_progress", " id = '" . $info['id'] . "' ");
        if (empty($info)) {
            $json['warn'] = '未找到上传的数据';
        } elseif (empty($upload_progress['id'])) {
            $json['warn'] = 1;
        } elseif (!empty($limitType) && !in_array($suffix, $limitType)) {
            $json['warn'] = '你上传的文件不在上传类型范围中';
        } else {
            switch ($info['target']) {
                case '客户':
                    if (!$this->power("client", "fileAdd")) {
                        $json['warn'] = "新增客户附件权限不足";
                    } else {
                        $kehu = query("kehu", " khid = '" . $info['target_id'] . "' ");
                        if (empty($kehu['khid'])) {
                            $json['warn'] = "未找到此客户";
                        } elseif (!in_array($this->control['stid'], explode(",", $kehu['see']))) {
                            $json['warn'] = "您不是此客户的负责人，也不是协作人";
                        } else {
                            //更新客户更新时间
                            update(array(
                                "table" => "kehu",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " khid = '$kehu[khid]' ",
                            ));
                        }
                    }
                    $powerType = "client";
                    $locationUrl = root . "control/adIndex.html?cla=client&fun=detail&menu=clientFile&id=" . $info['target_id'];
                    break;
                case '线索':
                    if (!$this->power("clue", "fileAdd")) {
                        $json['warn'] = "新增线索附件权限不足";
                    } else {
                        $clue = query("clue", " id = '" . $info['target_id'] . "' ");
                        if (empty($clue['id'])) {
                            $json['warn'] = "未找到此线索";
                        } elseif (!in_array($this->control['stid'], explode(",", $clue['see']))) {
                            $json['warn'] = "此线索既不是你的线索，你也不是协作人";
                        } else {
                            //更新更新时间
                            update(array(
                                "table" => "clue",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " id = '$clue[id]' ",
                            ));
                        }
                    }
                    $powerType = "clue";
                    $locationUrl = root . "control/adIndex.html?cla=clue&fun=detail&menu=clueFile&id=" . $info['target_id'];
                    break;
                case '商机':
                    if (!$this->power("opportunity", "fileAdd")) {
                        $json['warn'] = "新增线索附件权限不足";
                    } else {
                        $info = query("opportunity", " id = '" . $info['target_id'] . "' ");
                        if (empty($info['id'])) {
                            $json['warn'] = "未找到此商机";
                        } elseif (!in_array($this->control['stid'], explode(",", $info['see']))) {
                            $json['warn'] = "这不是你的商机，你也不是协作人";
                        } else {
                            //更新更新时间
                            update(array(
                                "table" => "opportunity",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " id = '$info[id]' ",
                            ));
                        }
                    }
                    $powerType = "opportunity";
                    $locationUrl = root . "control/adIndex.html?cla=opportunity&fun=detail&menu=opportunityFile&id=" . $info['target_id'];
                    break;
                case '采购合同':
                    $target_id = '';
                    if (!$this->power("purchaseContract", "fileAdd")) {
                        $json['warn'] = "新增合同附件权限不足";
                    } else {
                        if(empty($info['targetId'])){
                            $target_id = $info['target_id'];
                            $info = query("purchase_contract", " id = '" . $info['target_id'] . "' ");
                        }else{
                            $target_id = $info['targetId'];
                            $info = query("purchase_contract", " id = '" . $info['targetId'] . "' ");
                        }
                        if (empty($info['id'])) {
                            $json['warn'] = "未找到此合同";
                        }
                    }
                    $info['target'] = '采购合同';
                    $info['target_id'] = $target_id;
                    $powerType = "purchaseContract";
                    $locationUrl = root . "control/adIndex.html?cla=purchaseContract&fun=detail&menu=purchaseContractFile&id=" . $target_id;
                    break;
                case '委外合同':
                    if (!$this->power("outsourceContract", "fileAdd")) {
                        $json['warn'] = "新增合同附件权限不足";
                    } else {
                        $info = query("outsource_contract", " id = '" . $info['target_id'] . "' ");
                        if (empty($info['id'])) {
                            $json['warn'] = "未找到此合同";
                        }
                    }
                    $powerType = "outsourceContract";
                    $locationUrl = root . "control/adIndex.html?cla=outsourceContract&fun=detail&menu=outsourceContractFile&id=" . $info['target_id'];
                    break;
                case '设备':
                    if (!$this->power("equipment", "fileAdd")) {
                        $json['warn'] = "新增设备附件权限不足";
                    } else {
                        $info = query("equipment", " id = '" . $info['target_id'] . "' ");
                        if (empty($info['id'])) {
                            $json['warn'] = "未找到此设备";
                        }
                    }
                    $powerType = "equipment";
                    $locationUrl = root . "control/adIndex.html?cla=equipment&fun=detail&menu=equipmentFile&id=" . $info['target_id'];
                    break;
                case '项目':
                    if (!$this->power("orderAllot", "projectFileAdd")) {
                        $json['warn'] = "新增项目附件权限不足";
                    } else {
                        $project = query("project", " id = '" . $info['target_id'] . "' ");
                        $buyCarAllotNum = sqlNum("buycar_allot", "stid = '" . $this->control['stid'] . "' and projectId = '" . $info['target_id'] . "'");
                        if (empty($project['id'])) {
                            $json['warn'] = "未找到此项目";
                        } elseif ($buyCarAllotNum == 0) {
                            $json['warn'] = "此项目没有你的任务";
                        }
                    }
                    $powerType = "orderAllot";
                    $locationUrl = getenv("HTTP_REFERER");
                    if (strstr($locationUrl, "&menu=allotFile") == false) {
                        $locationUrl .= "&menu=allotFile";
                    }
                    break;
                case '销售合同':
                    if (!$this->power("salesContract", "fileAdd")) {
                        $json['warn'] = "上传销售合同附件权限不足";
                    } else {
                        $where = " id = '" . $info['target_id'] . "' ";
                        $info1 = query("sales_contract", $where);
                        if (empty($info1['id'])) {
                            $json['warn'] = "未找到此销售合同";
                        }
                    }
                    $powerType = "salesContract";
                    $locationUrl = root . "control/adIndex.html?cla=salesContract&fun=detail&menu=file&id=" . $info['target_id'];
                    break;
                case '销售计划':
                    $powerType = "saleOrderFile";
                    $locationUrl = root . "control/adIndex.html?cla=saleOrderFile&fun=home&menu=file&id=" . $info['target_id'];
                    break;
                case '物料档案':
                    if (!$this->power("material", "fileAdd")) {
                        $json['warn'] = "上传物料档案附件权限不足";
                    } else {
                        $where = " id = '" . $info['target_id'] . "' ";
                        $info1 = query("material", $where);
                        if (empty($info1['id'])) {
                            $json['warn'] = "未找到此物料档案";
                        }
                    }
                    $powerType = "material";
                    $locationUrl = root . "control/adIndex.html?cla=material&fun=detail&menu=materialFile&id=" . $info['target_id'];
                    break;
                case '供应商':
                    if (!$this->power("supplier", "fileAdd")) {
                        $json['warn'] = "上传供应商附件权限不足";
                    } else {
                        $where = " id = '" . $info['target_id'] . "' ";
                        $info1 = query("supplier", $where);
                        if (empty($info1['id'])) {
                            $json['warn'] = "未找到此供应商";
                        } elseif ($this->control['stid'] != $info1['stid'] and !$this->power('supplier', "seeAll")) {
                            $json['html'] = "这不是你的供应商，也没有查看所有供应商的权限";
                        }
                    }
                    $powerType = "supplier";
                    $locationUrl = root . "control/adIndex.html?cla=supplier&fun=detail&menu=supplierFile&id=" . $info['target_id'];
                    break;
                case '派遣单位':
                    if (!$this->power("laborCompany", "fileAdd")) {
                        $json['warn'] = "上传供应商附件权限不足";
                    } else {
                        $where = " id = '" . $info['target_id'] . "' ";
                        $info = query("labor_company", $where);
                        if (empty($info['id'])) {
                            $json['warn'] = "未找到此派遣单位";
                        }
                    }
                    $powerType = "laborCompany";
                    $locationUrl = root . "control/adIndex.html?cla=laborCompany&fun=detail&menu=file&id=" . $info['target_id'];
                    break;
                default:
                    $locationUrl = getenv("HTTP_REFERER");
                    $json['warn'] = "上传对象有误";
                    break;
            }
        }
        if(empty($json['warn'])){
            $result = (new shareClass())->saveFileTemp($file, $info['id'] . '_' . $this->post('chunk'));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                //判断分片是否全部上传完成
                $uploadStatus = true;
                for ($i = 1; $i <= $this->post('chunks'); $i++) {
                    if (!file_exists(serverRoot . 'file/temp/' . $info['id'] . "_" . $i)) {
                        $uploadStatus = false;
                        break;
                    }
                }
                if (!$uploadStatus) {
                    $progress = round($this->post('chunk') / $this->post('chunks') * 100, 2);
                } else {
                    //合并分片
                    $id = suiji();
                    $url = 'file/attachment/' . date("Ym");
                    $this->_mkdir($url);
                    $fileName = $id . '.' . $suffix;
                    $fp       = fopen(serverRoot . $url . '/' . $fileName, "w");
                    for ($i = 1; $i <= $this->post('chunks'); $i++) {
                        $chunkName = serverRoot . 'file/temp/' . $info['id'] . "_" . $i;
                        $chunkData = file_get_contents($chunkName);
                        fwrite($fp, $chunkData);
                        @unlink($chunkName); //删除分片文件
                    }
                    fclose($fp);
                    //插入文件记录
                    $field['src']             = $url . '/' . $fileName;
                    $field['name']             = $this->post('name');
                    $field['size']             = $this->post('size');
                    $field                     = array_merge($field, [
                        'id'     => $id,
                        "stid" => $this->control['stid'],
                        "target" => $info['target'],//目标对象
                        "targetId" => $info['target_id'],//上传对象ID号
                        "secret" => "否",
                        "format" => $suffix,
                        'time'   => date("Y-m-d H:i:s"),
                    ]);
                    $json['warn']              = insert([
                        'table' => "file",
                        'field' => $field
                    ]);
                    if ($json['warn'] == "新增成功") {
                        $state    = 1;
                        $progress = 100;
                    } else {
                        goto resp;
                    }
                }
                $json['warn'] = static::update([
                    "table" => 'upload_progress',
                    "field" => ['chunk' => $this->post('chunk'), 'state' => $state, 'updateTime' => $this->time],
                    "where" => " id = '" . $info['id'] . "' "
                ]);
                if ($json['warn'] == '更新成功') {
                    $json['warn']     = 2;
                    $json['state']    = $state;
                    $json['progress'] = $progress;
                    if ($state == 1) $_SESSION['warn'] = '上传成功';
                    //添加日志
                    $text = $this->control['name'] . "添加了一个附件：" . $info['target'] . "【" . $info['target_id'] . "】：" . $this->post('name');
                    $this->logText(array("type" => $powerType, "text" => $text));
                }
                goto resp;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /*附件上传*/
    public function fileUpload()
    {
        $powerType = '';
        $locationUrl = '';
        if (empty($this->post('target'))) {
            $warn = "目标对象为空";
        } elseif (empty($this->post('targetId'))) {
            $warn = "目标对象ID号为空";
        } else {
            switch ($this->post('target')) {
                case '客户':
                    if (!$this->power("client", "fileAdd")) {
                        $warn = "新增客户附件权限不足";
                    } else {
                        $kehu = query("kehu", " khid = '" . $this->post('targetId') . "' ");
                        if (empty($kehu['khid'])) {
                            $warn = "未找到此客户";
                        } elseif (!in_array($this->control['stid'], explode(",", $kehu['see']))) {
                            $warn = "您不是此客户的负责人，也不是协作人";
                        } else {
                            //更新客户更新时间
                            update(array(
                                "table" => "kehu",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " khid = '$kehu[khid]' ",
                            ));
                        }
                    }
                    $powerType = "client";
                    $locationUrl = root . "control/adIndex.html?cla=client&fun=detail&menu=clientFile&id=" . $this->post('targetId');
                    break;
                case '线索':
                    if (!$this->power("clue", "fileAdd")) {
                        $warn = "新增线索附件权限不足";
                    } else {
                        $clue = query("clue", " id = '" . $this->post('targetId') . "' ");
                        if (empty($clue['id'])) {
                            $warn = "未找到此线索";
                        } elseif (!in_array($this->control['stid'], explode(",", $clue['see']))) {
                            $warn = "此线索既不是你的线索，你也不是协作人";
                        } else {
                            //更新更新时间
                            update(array(
                                "table" => "clue",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " id = '$clue[id]' ",
                            ));
                        }
                    }
                    $powerType = "clue";
                    $locationUrl = root . "control/adIndex.html?cla=clue&fun=detail&menu=clueFile&id=" . $this->post('targetId');
                    break;
                case '商机':
                    if (!$this->power("opportunity", "fileAdd")) {
                        $warn = "新增线索附件权限不足";
                    } else {
                        $info = query("opportunity", " id = '" . $this->post('targetId') . "' ");
                        if (empty($info['id'])) {
                            $warn = "未找到此商机";
                        } elseif (!in_array($this->control['stid'], explode(",", $info['see']))) {
                            $warn = "这不是你的商机，你也不是协作人";
                        } else {
                            //更新更新时间
                            update(array(
                                "table" => "opportunity",
                                "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                                "where" => " id = '$info[id]' ",
                            ));
                        }
                    }
                    $powerType = "opportunity";
                    $locationUrl = root . "control/adIndex.html?cla=opportunity&fun=detail&menu=opportunityFile&id=" . $this->post('targetId');
                    break;
                case '采购合同':
                    if (!$this->power("purchaseContract", "fileAdd")) {
                        $warn = "新增合同附件权限不足";
                    } else {
                        $info = query("purchase_contract", " id = '" . $this->post('targetId') . "' ");
                        if (empty($info['id'])) {
                            $warn = "未找到此合同";
                        }
                    }
                    $powerType = "purchaseContract";
                    $locationUrl = root . "control/adIndex.html?cla=purchaseContract&fun=detail&menu=purchaseContractFile&id=" . $this->post('targetId');
                    break;
                case '委外合同':
                    if (!$this->power("outsourceContract", "fileAdd")) {
                        $warn = "新增合同附件权限不足";
                    } else {
                        $info = query("outsource_contract", " id = '" . $this->post('targetId') . "' ");
                        if (empty($info['id'])) {
                            $warn = "未找到此合同";
                        }
                    }
                    $powerType = "outsourceContract";
                    $locationUrl = root . "control/adIndex.html?cla=outsourceContract&fun=detail&menu=outsourceContractFile&id=" . $this->post('targetId');
                    break;
                case '设备':
                    if (!$this->power("equipment", "fileAdd")) {
                        $warn = "新增设备附件权限不足";
                    } else {
                        $info = query("equipment", " id = '" . $this->post('targetId') . "' ");
                        if (empty($info['id'])) {
                            $warn = "未找到此设备";
                        }
                    }
                    $powerType = "equipment";
                    $locationUrl = root . "control/adIndex.html?cla=equipment&fun=detail&menu=equipmentFile&id=" . $this->post('targetId');
                    break;
                case '项目':
                    if (!$this->power("orderAllot", "projectFileAdd")) {
                        $warn = "新增项目附件权限不足";
                    } else {
                        $project = query("project", " id = '" . $this->post('targetId') . "' ");
                        $buyCarAllotNum = sqlNum("buycar_allot", "stid = '" . $this->control['stid'] . "' and projectId = '" . $this->post('targetId') . "'");
                        if (empty($project['id'])) {
                            $warn = "未找到此项目";
                        } elseif ($buyCarAllotNum == 0) {
                            $warn = "此项目没有你的任务";
                        }
                    }
                    $powerType = "orderAllot";
                    $locationUrl = getenv("HTTP_REFERER");
                    if (strstr($locationUrl, "&menu=allotFile") == false) {
                        $locationUrl .= "&menu=allotFile";
                    }
                    break;
                case '销售合同':
                    if (!$this->power("salesContract", "fileAdd")) {
                        $warn = "上传销售合同附件权限不足";
                    } else {
                        $where = " id = '" . $this->post('targetId') . "' ";
                        $info = query("sales_contract", $where);
                        if (empty($info['id'])) {
                            $warn = "未找到此销售合同";
                        } elseif ($this->control['stid'] != $info['stid'] || $this->control['stid'] != $info['salesman']) {
                            $warn = "这不是你的销售合同";
                        }
                    }
                    $powerType = "salesContract";
                    $locationUrl = root . "control/adIndex.html?cla=salesContract&fun=detail&menu=file&id=" . $this->post('targetId');
                    break;
                case '物料档案':
                    if (!$this->power("material", "fileAdd")) {
                        $warn = "上传物料档案附件权限不足";
                    } else {
                        $where = " id = '" . $this->post('targetId') . "' ";
                        $info = query("material", $where);
                        if (empty($info['id'])) {
                            $warn = "未找到此物料档案";
                        }
                    }
                    $powerType = "material";
                    $locationUrl = root . "control/adIndex.html?cla=material&fun=detail&menu=materialFile&id=" . $this->post('targetId');
                    break;
                case '供应商':
                    if (!$this->power("supplier", "fileAdd")) {
                        $warn = "上传供应商附件权限不足";
                    } else {
                        $where = " id = '" . $this->post('targetId') . "' ";
                        $info = query("supplier", $where);
                        if (empty($info['id'])) {
                            $warn = "未找到此供应商";
                        } elseif ($this->control['stid'] != $info['stid'] and !$this->power('supplier', "seeAll")) {
                            $json['html'] = "这不是你的供应商，也没有查看所有供应商的权限";
                        }
                    }
                    $powerType = "supplier";
                    $locationUrl = root . "control/adIndex.html?cla=supplier&fun=detail&menu=supplierFile&id=" . $this->post('targetId');
                    break;
                case '派遣单位':
                    if (!$this->power("laborCompany", "fileAdd")) {
                        $warn = "上传供应商附件权限不足";
                    } else {
                        $where = " id = '" . $this->post('targetId') . "' ";
                        $info = query("labor_company", $where);
                        if (empty($info['id'])) {
                            $warn = "未找到此派遣单位";
                        }
                    }
                    $powerType = "laborCompany";
                    $locationUrl = root . "control/adIndex.html?cla=laborCompany&fun=detail&menu=file&id=" . $this->post('targetId');
                    break;
                default:
                    $locationUrl = getenv("HTTP_REFERER");
                    $warn = "上传对象有误";
                    break;
            }
        }
        if (empty($warn)) {
            $fileName = "file";                        //附件上传域名称
            $tmp_name = $_FILES[$fileName]['tmp_name'];//临时文件名
            $name = $_FILES[$fileName]['name'];    //附件名称
            $nameArr = explode('.', $name);
            $suffix = end($nameArr);//附件后缀
            $filesize = filesize($tmp_name);
            if (!in_array($suffix, explode(",", para("fileFormat")))) {
                $warn = "文件后缀【" . $suffix . "】不在白名单中";
            } elseif (sqlNum("file", " targetId = '" . $this->post('targetId') . "' and name = '$name' ") > 0) {
                $warn = "此附件已存在";
            } else {
                $id = suiji();
                $url = "file/attachment/" . date("Ym");
                if (!file_exists(serverRoot . $url)) {
                    self::_mkdir($url);
                }
                $src = $url . "/" . $id . "." . $suffix;//保存附件的根目录路径
                $warn = insert(array(
                    "table" => "file",
                    "field" => array(
                        "id" => $id,
                        "stid" => $this->control['stid'],
                        "target" => $this->post('target'),//目标对象
                        "targetId" => $this->post('targetId'),//上传对象ID号
                        "name" => $name,
                        "secret" => "否",
                        "format" => $suffix,
                        "size" => $filesize,
                        "src" => $src,
                        "time" => date("Y-m-d H:i:s"),
                    ),
                ));
                if ($warn == "新增成功") {
                    move_uploaded_file($tmp_name, serverRoot . $src);
                    //添加日志
                    $text = $this->control['name'] . "添加了一个附件：" . $this->post('target') . "【" . $this->post('targetId') . "】：" . $name;
                    $this->logText(array("type" => $powerType, "text" => $text));
                }
            }
        }
        $_SESSION['warn'] = $warn;
        header("location:" . $locationUrl);
        exit(0);
    }

    /*删除附件*/
    public function delete()
    {
        if (empty($this->post('fileId'))) {
            $json['warn'] = "你一个附件都没有选择呢";
        } elseif (empty($this->post('password'))) {
            $json['warn'] = "请输入管理员登录密码";
        } elseif (verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = "管理员登录密码输入错误";
        } else {
            $log = "";
            $x = 0;
            $type = '';
            foreach ($this->post('fileId') as $id) {
                //查询附件基本信息
                $file = query("file", " id = '$id' ");
                $finger = $type = "";
                $log .= "\n" . $file['name'];
                //判断附件类型
                if ($file['target'] == "采购合同") {
                    $type = "purchaseContract";
                    $info = query("purchase_contract", " id = '$file[targetId]' ");
                    if (!$this->power("purchaseContract", "fileDel")) {
                        $json['warn'] = "删除采购合同附件权限不足";
                        break;
                    } else {
                        $finger = 2;
                        $log .= "删除成功，采购合同名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=purchaseContract&fun=detail&menu=purchaseContractFile&id=" . $info['id'];
                    }
                }elseif ($file['target'] == "委外合同") {
                    $type = "outsourceContract";
                    $info = query("outsource_contract", " id = '$file[targetId]' ");
                    if (!$this->power("outsourceContract", "fileDel")) {
                        $json['warn'] = "删除委外合同附件权限不足";
                        break;
                    } else {
                        $finger = 2;
                        $log .= "删除成功，委外合同名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=outsourceContract&fun=detail&menu=outsourceContractFile&id=" . $info['id'];
                    }
                } elseif ($file['target'] == "商机") {
                    $type = "opportunity";
                    $info = query("opportunity", " id = '$file[targetId]' ");
                    if (!$this->power("opportunity", "fileDel")) {
                        $json['warn'] = "删除商机附件权限不足";
                        break;
                    } elseif (!in_array($this->control['stid'], array($file['stid'], $info['manager']))) {
                        $log .= "不是你的商机，也不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，商机名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=opportunity&fun=detail&menu=opportunityFile&id=" . $info['id'];
                    }
                } elseif ($file['target'] == "客户") {
                    $type = "client";
                    $kehu = query("kehu", " khid = '$file[targetId]' ");
                    if (!$this->power("client", "fileDel")) {
                        $json['warn'] = "删除客户附件权限不足";
                        break;
                    } elseif (!in_array($this->control['stid'], array($file['stid'], $kehu['stid']))) {
                        $log .= "不是你的客户，也不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，客户名称：" . $kehu['companyName'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=client&fun=detail&menu=clientFile&id=" . $kehu['khid'];
                    }
                } elseif ($file['target'] == "线索") {
                    $type = "clue";
                    $info = query("clue", " id = '$file[targetId]' ");
                    if (!$this->power("clue", "fileDel")) {
                        $json['warn'] = "删除线索附件权限不足";
                        break;
                    } elseif (!in_array($this->control['stid'], array($file['stid'], $info['manager']))) {
                        $log .= "不是你的客户，也不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，线索名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=clue&fun=detail&menu=clueFile&id=" . $info['id'];
                    }
                } elseif ($file['target'] == "订单") {
                    $type = "order";
                    $buyCar = query("buycar", " id = '$file[targetId]' ");
                    if (!$this->power("order", "fileDel")) {
                        $json['warn'] = "删除订单附件权限不足";
                        break;
                    } elseif (!in_array($this->control['stid'], array($file['stid'], $buyCar['stid']))) {//如果既不是自己上传的，订单也不是自己的，则不允许删除
                        $log .= "不是你的订单，也不是你上传的附件。";
                    } elseif ($buyCar['workFlow'] != "草稿") {
                        $log .= "的订单【" . $buyCar['name'] . "】不处于草稿状态，不能删除。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，订单名称：" . $buyCar['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=order&fun=detail&menu=orderFile&id=" . $buyCar['id'];
                    }
                } elseif ($file['target'] == "销售计划") {
                    $type = "saleOrderFile";
                    if (!in_array($this->control['stid'], array($file['stid'], $file['targetId']))) {//如果既不是自己上传的，订单也不是自己的，则不允许删除
                        $log .= "不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功。";
                        $json['href'] = root . "control/adIndex.html?cla=saleOrderFile&fun=home";
                    }
                } elseif ($file['target'] == "项目") {
                    $type = "project";
                    $project = query("project", " id = '$file[targetId]' ");
                    if (!$this->power("orderAllot", "projectFileDel")) {
                        $json['warn'] = "删除项目附件权限不足";
                        break;
                    } elseif ($file['stid'] != $this->control['stid']) {
                        $log .= "不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，项目名称：" . $project['name'] . "。";
                        $json['href'] = getenv("HTTP_REFERER");//传送数据过来的页面名称
                        if (strstr($json['href'], "menu=allotFile") !== false) {
                            $json['href'] .= "&menu=allotFile";
                        }
                    }
                } elseif ($file['target'] == "派遣单位") {
                    $type = "laborCompany";
                    $labor_company = query("labor_company", " id = '$file[targetId]' ");
                    if (!$this->power("laborCompany", "fileDel")) {
                        $json['warn'] = "删除派遣单位附件权限不足";
                        break;
                    } elseif ($file['stid'] != $this->control['stid']) {
                        $log .= "不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，派遣单位名称：" . $labor_company['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=laborCompany&fun=detail&menu=laborCompanyFile&id=" . $labor_company['id'];
                    }
                } elseif ($file['target'] == "销售合同") {
                    $type = "salesContract";
                    $info = query("sales_contract", " id = '$file[targetId]' ");
                    if (!$this->power("salesContract", "fileDel")) {
                        $json['warn'] = "删除销售合同附件权限不足";
                        break;
                    } else {
                        $finger = 2;
                        $log .= "删除成功，销售合同名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=salesContract&fun=detail&menu=file&id=" . $info['id'];
                    }
                } elseif ($file['target'] == "物料档案") {
                    $type = "material";
                    $info = query("material", " id = '$file[targetId]' ");
                    if (!$this->power("material", "fileDel")) {
                        $json['warn'] = "删除物料档案附件权限不足";
                        break;
                    } elseif ($file['stid'] != $this->control['stid']) {
                        $log .= "不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，物料名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=material&fun=detail&menu=materialFile&id=" . $info['id'];
                    }
                } elseif ($file['target'] == "供应商") {
                    $type = "supplier";
                    $info = query("supplier", " id = '$file[targetId]' ");
                    if (!$this->power("supplier", "fileDel")) {
                        $json['warn'] = "删除供应商附件权限不足";
                        break;
                    } elseif ($this->control['stid'] != $info['stid'] and $file['stid'] != $this->control['stid']) {
                        $log .= "不是你的供应商，也不是你上传的附件。";
                    } else {
                        $finger = 2;
                        $log .= "删除成功，供应商名称：" . $info['name'] . "。";
                        $json['href'] = root . "control/adIndex.html?cla=supplier&fun=detail&menu=supplierFile&id=" . $info['id'];
                    }
                }
                if ($finger == 2) {
                    //删除附件
                    fileDelete($file['src']);
                    //删除附件基本信息
                    delete(array("table" => "file", "where" => " id = '$id' "));
                    //计数
                    $x++;
                }
            }
            if (empty($json['warn'])) {
                //日志
                $text = $this->control['name'] . "删除了附件，结果如下：" . $log;
                $this->logText(array("type" => $type, "text" => $text));
                //返回信息
                $_SESSION['warn'] = "删除了" . $x . "个附件，详情见日志";
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 删除附件
     * @param $id
     */
    public static function deleteFile($id){
        $all = find(['table'=>'file','where'=>"targetId = '$id'"]);
        foreach ($all['array'] as $array){
            fileDelete($array['src']);
        }
        delete(['table'=>'file','where'=>"targetId = '$id'"]);
    }
}
